package cn.butcher21.utils;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * butcher create in 2021/04/24/9:57
 * <p>
 * 数据库连接工具
 */
public class DBUtil {
    private Connection conn = null;
    private PreparedStatement ps = null;
    private ResultSet rs = null;
    private String user;
    private String password;
    private String url;
    private String path;

    public DBUtil() throws IOException, ClassNotFoundException, SQLException {
        Properties properties = new Properties();
        properties.load(this.getClass().getResourceAsStream("/dbConfig.properties"));
        this.user = properties.getProperty("user");
        this.password = properties.getProperty("password");
        this.url = properties.getProperty("url");
        this.path = properties.getProperty("path");

        Class.forName(this.path);

        this.conn = DriverManager.getConnection(this.url, this.user, this.password);
    }

    public Connection getConn() {
        return conn;
    }

    public void setConn(Connection conn) {
        this.conn = conn;
    }

    public PreparedStatement getPs(String sql) throws SQLException {
        ps = this.conn.prepareStatement(sql);
        return ps;
    }

    public void setPs(PreparedStatement ps) {
        this.ps = ps;
    }

    public ResultSet getRs(ResultSet rs) {
        this.rs = rs;
        return rs;
    }

    public void setRs(ResultSet rs) {
        this.rs = rs;
    }

    public void close() throws SQLException {
        if (rs != null) {
            rs.close();
        }
        if (ps != null) {
            ps.close();
        }
        if (conn != null) {
            conn.close();
        }
    }

    public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException {
        DBUtil dbUtil = new DBUtil();
        String sql = "SELECT * FROM T_USER";
        PreparedStatement ps = dbUtil.getPs(sql);
        ResultSet rs = dbUtil.getRs(ps.executeQuery());
        if (rs.next()) {
            System.out.println(rs.getString("u_name"));
        }
    }
}
